//
//  UIImage+extension.swift
//  iUtil
//
//  Created by wendachuan on 19/3/22.
//  Copyright © 2019年 wendachuan. All rights reserved.
//

import UIKit

public extension UIImage {
    /// 返回限定了数据大小的jpeg数据
    ///
    /// - parameter maxBytes: 限定字节数
    /// - returns: 返回的数据
    func imageJPEGRepresentationWithMaxBytes(_ maxBytes: Int) -> Data? {
        if let data = self.jpegData(compressionQuality: 1) {
            if data.count <= maxBytes {
                return data
            }

            var image = self
            while true {
                let newSize = CGSize(width: image.size.width * 0.75, height: image.size.height * 0.75)
                UIGraphicsBeginImageContext(newSize)
                image.draw(in: CGRect(origin: CGPoint.zero, size: newSize))
                let newImage = UIGraphicsGetImageFromCurrentImageContext()
                UIGraphicsEndImageContext()

                if newImage != nil {
                    if let tmpData = newImage?.jpegData(compressionQuality: 1) {
                        if tmpData.count < maxBytes {
                            return tmpData
                        } else {
                            image = newImage!
                        }
                    } else {
                        return nil
                    }
                } else {
                    return nil
                }
            }
        } else {
            return nil
        }
    }

    /// 返回缩放后的图片
    ///
    /// - parameter newSize: 缩放后的尺寸
    /// - returns: 缩放后的图片
    func resizedImage(_ newSize: CGSize) -> UIImage {
        UIGraphicsBeginImageContext(newSize)
        self.draw(in: CGRect(origin: CGPoint.zero, size: newSize))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage!
    }
    
    /// 用颜色创建图片
    ///
    /// - Parameters:
    ///   - color:
    ///   - size:
    class func imageWithColor(_ color: UIColor, size: CGSize) -> UIImage? {
        let rect = CGRect.init(x: 0, y: 0, width: size.width, height: size.height)
        UIGraphicsBeginImageContext(rect.size)
        if let context = UIGraphicsGetCurrentContext() {
            context.setFillColor(color.cgColor)
            context.fill(rect)
            let img = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return img
        } else {
            return nil
        }
    }
}
